import SockJS from 'sockjs-client';
import { userStore } from '@/store/user';
class SocketService {
    constructor() {
        // 基础配置
        this.socketUrl = '';
        this.socket = null;
        this.connected = false;

        // 心跳配置
        this.heartbeatInterval = 30000;
        this.heartbeatCheckInterval = 15000;
        this.lastHeartbeatTime = 0;
        this.heartbeatTimer = null;
        this.heartbeatCheckTimer = null;

        // 重连配置
        this.reconnectInterval = 5000;
        this.maxReconnectAttempts = 10;
        this.reconnectAttempts = 0;
        this.reconnectTimer = null;

        this.isManualDisconnect = false;
        // 新增：标记是否正在执行重连（防止重复触发）
        this.isReconnecting = false;
        // 事件回调
        this.callbacks = {
            connect: [],
            disconnect: [],
            error: []
        };

        // 订阅映射表
        this.subscriptions = new Map();

        // 绑定页面可见性/焦点事件（监听锁屏解锁）
        this.bindVisibilityListeners();
    }

    // 绑定页面可见性和焦点事件
    bindVisibilityListeners() {
        // 监听页面可见性变化（锁屏时不可见，解锁时可见）
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.checkReconnectOnUnlock();
            }
        });

        // 监听页面获得焦点（解锁后可能触发）
        window.addEventListener('focus', () => {
            this.checkReconnectOnUnlock();
        });

        // 监听网络恢复（锁屏可能导致网络断开）
        window.addEventListener('online', () => {
            this.checkReconnectOnUnlock();
        });
    }

    // 优化：解锁后检查并尝试重连（严格判断条件）
    checkReconnectOnUnlock() {
        // 严格条件：
        // 1. 未连接 2. 非主动断开 3. 不在重连中 4. 有有效连接地址 5. 未达到最大重连次数
        const shouldReconnect = !this.connected &&
            !this.isManualDisconnect &&
            !this.isReconnecting &&
            !!this.socketUrl
        // &&
        // this.reconnectAttempts < this.maxReconnectAttempts;

        if (shouldReconnect) {
            console.log('检测到页面恢复可见，执行解锁重连');
            // 清除原有重连定时器（避免延迟重连和立即重连冲突）
            if (this.reconnectTimer) {
                clearTimeout(this.reconnectTimer);
                this.reconnectTimer = null;
            }
            this.connect(); // 立即发起连接
        } else {
            // 输出日志，方便排查误触发原因
            console.log('解锁重连条件不满足：', {
                connected: this.connected,
                isManualDisconnect: this.isManualDisconnect,
                isReconnecting: this.isReconnecting,
                hasSocketUrl: !!this.socketUrl,
                reconnectAttempts: this.reconnectAttempts,
                maxReconnectAttempts: this.maxReconnectAttempts
            });
        }
    }

    // 初始化配置
    init(url, options = {}) {
        this.socketUrl = url;
        if (options.heartbeatInterval) this.heartbeatInterval = options.heartbeatInterval;
        if (options.heartbeatCheckInterval) this.heartbeatCheckInterval = options.heartbeatCheckInterval;
        if (options.reconnectInterval) this.reconnectInterval = options.reconnectInterval;
        if (options.maxReconnectAttempts) this.maxReconnectAttempts = options.maxReconnectAttempts;
        return this;
    }

    // 连接WebSocket（新增 isReconnecting 标记）
    connect() {
        // 防止重复连接
        if (this.connected || this.isReconnecting) return;

        this.isReconnecting = true; // 标记为正在重连
        try {
            this.socket = new SockJS(this.socketUrl);
            this.socket.onopen = () => this.onOpen();
            this.socket.onmessage = (e) => this.onMessage(e);
            this.socket.onerror = (e) => this.onError(e);
            this.socket.onclose = (e) => this.onClose(e);
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            this.triggerCallbacks('error', error);
            this.isReconnecting = false; // 连接失败，重置标记
            this.scheduleReconnect();
        }
    }

    // 连接成功处理（重置 isReconnecting）
    onOpen() {
        if (this.socketUrl === 'https://new.uhx.io/currency/websocket') {
            userStore().setCurrencySocket(true);
        } else if (this.socketUrl === 'https://new.uhx.io/cct/cct-websocket') {
            userStore().setCctSocket(true);
        } else if (this.socketUrl === 'https://new.uhx.io/futures/futures-websocket') {
            userStore().setFuturesSocket(true)
        } else {
            userStore().setHycurrencySocket(true)
        }
        this.connected = true;
        this.reconnectAttempts = 0;
        this.isReconnecting = false; // 重连成功，重置标记
        this.startHeartbeat();
        this.triggerCallbacks('connect');
    }

    // 消息接收处理（保持不变）
    onMessage(event) {
        try {
            const data = event.data;
            const lines = data.split('\n');
            const command = lines[0];

            if (command === 'CONNECTED' || command === 'RECEIPT') {
                this.updateHeartbeat();
                return;
            }

            const headers = {};
            let bodyStart = 0;
            for (let i = 1; i < lines.length; i++) {
                if (lines[i] === '') {
                    bodyStart = i + 1;
                    break;
                }
                const colonIndex = lines[i].indexOf(':');
                if (colonIndex > 0) {
                    const key = lines[i].substring(0, colonIndex).trim();
                    const value = lines[i].substring(colonIndex + 1).trim();
                    headers[key] = value;
                }
            }

            const bodyRaw = lines.slice(bodyStart).join('\n').replace(/\0$/, '');
            const message = JSON.parse(bodyRaw);
            const subscriptionKey = headers.subscription
            if (!subscriptionKey) {
                console.warn('消息缺少订阅标识（subscription），无法分发:', message);
                return;
            }
            const subCallbacks = this.subscriptions.get(subscriptionKey) || [];
            subCallbacks.forEach(callback => {
                try {
                    callback(message.data || message);
                } catch (cbError) {
                    console.error(`订阅[${subscriptionKey}]的回调执行失败:`, cbError);
                }
            });

        } catch (parseError) {
            console.error('消息解析失败:', parseError);
            this.triggerCallbacks('error', {
                type: 'MESSAGE_PARSE_ERROR',
                rawData: event.data,
                error: parseError
            });
        }
    }

    // 错误处理（重置 isReconnecting）
    onError(error) {
        console.error('WebSocket错误:', error);
        this.isReconnecting = false; // 错误时，重置重连标记
        this.triggerCallbacks('error', error);
    }

    // 关闭处理（重置 isReconnecting）
    onClose(event) {
        console.log('WebSocket连接关闭:', event);
        this.isReconnecting = false; // 关闭时，重置重连标记
        if (this.connected) {
            this.connected = false;
            this.stopHeartbeat();
            this.triggerCallbacks('disconnect', event);
            this.subscriptions.clear();
        }
        if (!this.isManualDisconnect) {
            this.scheduleReconnect();
        } else {
            this.isManualDisconnect = false;
        }
    }

    // 安排重连（保持不变）
    scheduleReconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.error(`已达到最大重连次数(${this.maxReconnectAttempts})，停止重连`);
            this.triggerCallbacks('error', new Error(`已达到最大重连次数(${this.maxReconnectAttempts})`));
            return;
        }
        if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
        this.reconnectAttempts++;
        console.log(`将在${this.reconnectInterval / 1000}秒后进行第${this.reconnectAttempts}次重连...`);
        this.reconnectTimer = setTimeout(() => {
            this.reconnectTimer = null;
            this.connect();
        }, this.reconnectInterval);
    }

    // 启动心跳检测（保持不变）
    startHeartbeat() {
        this.stopHeartbeat();
        this.lastHeartbeatTime = Date.now();

        this.heartbeatTimer = setInterval(() => {
            if (this.connected && this.socket) {
                try {
                    this.send('CONNECT\naccept-version:1.1\nheart-beat:10000,10000\n\n\u0000');
                } catch (error) {
                    console.error('发送心跳失败:', error);
                }
            }
        }, this.heartbeatInterval);

        this.heartbeatCheckTimer = setInterval(() => {
            const now = Date.now();
            if (now - this.lastHeartbeatTime > this.heartbeatInterval * 2) {
                console.warn('心跳超时，连接可能已断开');
                this.disconnect('心跳超时');
                if (this.reconnectTimer) {
                    clearTimeout(this.reconnectTimer);
                    this.reconnectTimer = null;
                }
                this.connect(); // 立即发起连接
            }
        }, this.heartbeatCheckInterval);
    }

    // 停止心跳检测（保持不变）
    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
        if (this.heartbeatCheckTimer) {
            clearInterval(this.heartbeatCheckTimer);
            this.heartbeatCheckTimer = null;
        }
    }

    // 更新最后一次心跳时间（保持不变）
    updateHeartbeat() {
        this.lastHeartbeatTime = Date.now();
    }

    // 发送消息（保持不变）
    send(data) {
        if (!this.connected || !this.socket) {
            console.error('WebSocket未连接，无法发送消息');
            return false;
        }
        try {
            const sendData = typeof data === 'object' ? JSON.stringify(data) : data;
            this.socket.send(sendData);
            return true;
        } catch (error) {
            this.triggerCallbacks('error', error);
            return false;
        }
    }

    // 断开连接（保持不变）
    disconnect(reason = '主动断开连接') {
        if (this.connected && this.socket) {
            this.isManualDisconnect = true;
            this.socket.close();
            userStore().setCurrencySocket(false)
            userStore().setCctSocket(false)
            console.log(`WebSocket已断开: ${reason}`);
            this.connected = false;
            this.stopHeartbeat();

            if (this.reconnectTimer) {
                clearTimeout(this.reconnectTimer);
                this.reconnectTimer = null;
            }

            this.subscriptions.clear();
            this.triggerCallbacks('disconnect', reason);
        }
    }

    // 订阅主题（保持不变）
    subscribe(id, subscriptionKey, callback, autoSendSubscribeCmd = true) {
        if (!subscriptionKey || typeof callback !== 'function') {
            console.error('订阅失败：订阅标识和回调函数不能为空');
            return false;
        }
        if (!this.connected) {
            console.error('订阅失败：WebSocket未连接');
            return false;
        }

        if (!this.subscriptions.has(id)) {
            this.subscriptions.set(id, []);
        }
        const callbacks = this.subscriptions.get(id);
        if (!callbacks.includes(callback)) {
            callbacks.push(callback);
        }

        if (autoSendSubscribeCmd) {
            const subscribeCmd = `SUBSCRIBE\nid:${id}\ndestination:${subscriptionKey}\n\n\u0000`;
            this.send(subscribeCmd);
            console.log(`已订阅主题[${subscriptionKey}][${id}]`);
        }

        return true;
    }

    // 取消订阅（保持不变）
    unsubscribe(id, subscriptionKey, callback, autoSendUnsubscribeCmd = true) {
        if (!id) {
            console.error('取消订阅失败：订阅标识不能为空');
            return false;
        }

        if (this.subscriptions.has(id)) {
            const callbacks = this.subscriptions.get(id);
            if (callback) {
                this.subscriptions.set(
                    id,
                    callbacks.filter(cb => cb !== callback)
                );
                if (this.subscriptions.get(id).length === 0) {
                    this.subscriptions.delete(id);
                }
            } else {
                this.subscriptions.delete(id);
            }
        }

        if (autoSendUnsubscribeCmd) {
            const unsubscribeCmd = `UNSUBSCRIBE\nid:${id}\n\n\u0000`;
            this.send(unsubscribeCmd);
            console.log(`已取消订阅主题[${subscriptionKey}][${id}]`);
        }

        return true;
    }

    // 注册事件回调（保持不变）
    on(event, callback) {
        if (['connect', 'disconnect', 'error'].includes(event) && typeof callback === 'function') {
            this.callbacks[event].push(callback);
        }
    }

    // 移除事件回调（保持不变）
    off(event, callback) {
        if (['connect', 'disconnect', 'error'].includes(event)) {
            this.callbacks[event] = this.callbacks[event].filter(cb => cb !== callback);
        }
    }

    // 触发事件回调（保持不变）
    triggerCallbacks(event, data) {
        if (this.callbacks[event]) {
            this.callbacks[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`触发${event}回调失败:`, error);
                }
            });
        }
    }

    // 销毁实例（保持不变）
    destroy() {
        this.disconnect('实例销毁');
        this.callbacks = { connect: [], disconnect: [], error: [] };
        this.subscriptions.clear();
    }
}

export default SocketService